package cn.campus.controller.article;

import cn.campus.enums.article.ResultEnum;
import cn.campus.exception.article.ArticleException;
import cn.campus.pojo.User;
import cn.campus.pojo.article.dto.CommentDTO;
import cn.campus.pojo.article.dto.PageInfo;
import cn.campus.pojo.article.vo.ResultVO;
import cn.campus.service.article.CommentService;
import cn.campus.util.ResultVoUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * 评论控制器
 * Created by linyanbin on 2018/9/21.
 */
@RestController
@RequestMapping("/api/articles/comments")
@Slf4j
public class CommentController {

    @Autowired
    private CommentService commentService;

    /**
     * 获取一篇文章下的评论列表，分页
     * @param articleId 文章ID
     * @param page  当前页
     * @param size  每页显示记录数
     * @return
     */
    @GetMapping("/p/{articleId}")
    public ResultVO<Object> findPageByArticleId(@PathVariable("articleId") String articleId,
                                                             @RequestParam(value = "page", defaultValue = "1") Integer page,
                                                             @RequestParam(value = "size", defaultValue = "5") Integer size) {
        PageInfo<CommentDTO> dtoPageInfo = commentService.findAllByArticleId(articleId, page, size);
        return ResultVoUtils.success(dtoPageInfo);
    }

    /**
     * 获取一篇文章下的评论列表，不分页
     * @param articleId 文章ID
     * @return
     */
    @GetMapping("/{articleId}")
    public ResultVO<Object> findListByArticleId(@PathVariable("articleId") String articleId) {
        List<CommentDTO> commentDTOList = commentService.findListByArticleId(articleId);
        return ResultVoUtils.success(commentDTOList);
    }

    /**
     * 添加评论
     * @param articleId     文章ID
     * @param commentContent    评论内容
     * @param session
     * @return
     */
    @PostMapping
    public ResultVO createComment(String articleId, String commentContent, HttpSession session) {
        CommentDTO commentDTO = new CommentDTO();
        commentDTO.setArticleId(articleId);
        commentDTO.setCommentContent(commentContent);
        User user = (User)session.getAttribute("user");
        if (user == null) {
            throw new ArticleException(ResultEnum.USER_NOT_LOGIN);
        }
        commentDTO.setFromId(user.getUser_id());

        commentService.save(commentDTO);
        return ResultVoUtils.success();
    }
}
